class RatingMark < ActiveRecord::Base
  set_primary_keys :user_id, :target_type, :target_id

  RATINGS_STATES = ["Positive", "Negative"]

  belongs_to :user
  belongs_to :target, :polymorphic => true

  validates_presence_of   :user, :target, :state
  validates :state,       :inclusion => RATINGS_STATES
  validates :target_type, :inclusion => ["Document", "Comment"]

  def positive?
    self.state == "Positive"
  end
  def negative?
    self.state == "Negative"
  end
  def positive
    self.state = "Positive"
  end
  def negative
    self.state = "Negative"
  end

  def up
    unless self.user == self.target.user
      if negative? || new_record?
        if self.target.increment!(:rating)
          positive
          save
        end
      end
    end
  end

  def down
    unless self.user == self.target.user
      if positive? || new_record?
        if self.target.decrement!(:rating)
          negative
          save
        end
      end
    end
  end
end
